package test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author tongchen
 * @create 2023-02-18 11:00
 */
public class UDPchoClient {
    //定义服务器的地址和端口号
    private String address;
    private int port;
    private DatagramSocket socket;
    //初始化端口号和目标地址
    public UDPchoClient(String address, int port) throws SocketException {
        this.address = address;
        this.port = port;
        this.socket=new DatagramSocket();
    }
    //启动程序
    public void start() throws IOException {
        System.out.println("客户端启动......");
        //输入请求数据
        while(true){
            System.out.println("请输入请求数据");
            Scanner scanner=new Scanner(System.in);
            String request=scanner.nextLine();
            //与服务端建立连接
            InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port);
            //进行数据的封装
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8), request.getBytes().length, inetSocketAddress);
            //发送数据
            socket.send(requestPacket);
            //创建接收packet
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            //接收数据
            socket.receive(responsePacket);
            //解析数据
            String response=new String(responsePacket.getData(), 0, responsePacket.getLength(), "utf-8");
            //打印解析到的数据
            System.out.printf("request=%s,response=%s\n",request,response);
        }

    }

    public static void main(String[] args) throws IOException {
        //创建客户端
        UDPchoClient udPchoClient = new UDPchoClient("127.0.0.1", 9091);
        //启动客户端
        udPchoClient.start();
    }
}
